package main
import (
    "os/exec"
    "strings"
    "regexp"
    "strconv"
    "time"
)

type TrafficLog struct {
    Start_Time int
    End_Time   int
    Traffic    int
}

func Analyze_Single_File(capture_result string) []TrafficLog {
    analyze_result := make([]TrafficLog,0,20)
    output_bytes, err:= exec.Command("tshark","-q","-z","io,stat,10","-r",capture_result).CombinedOutput()
    if err == exec.ErrNotFound {
	panic(err)
    }
    output := string(output_bytes)
    for _, st := range strings.Split(output, "\n") {
	if strings.Contains(st, "<>") {
	    re, err := regexp.Compile("\\d+")
	    if err != nil {
		panic(err)
	    }
	    match_result := re.FindAllString(st, -1)
	    analyze_result = append(analyze_result, TrafficLog{
		atoi(match_result[0]),
		atoi(match_result[1]),
		atoi(match_result[3]),
	    })
	}
    }
    return analyze_result
}

func Analyze(capture_3G,capture_wifi string) AnalyzeData {
    result := AnalyzeData{}
    result.ID = NewID()
    result.Start_time = time.Now()
    result.Data_3G = Analyze_Single_File(capture_3G)
    result.Data_wifi = Analyze_Single_File(capture_wifi)
    result.Finish_time = time.Now()
    return result
}

func atoi(str string) int {
    result,_ := strconv.Atoi(str)
    return result
}
